package com.web.actions.login;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionMessage;

import com.web.actions.AbstractAction;

import com.ejemplo.bt.usuarios.services.UsuarioServices;
import com.ejemplo.bt.usuarios.vo.Usuario;

import com.web.actions.login.vo.LoginActionForm;
import com.web.mail.Mail;

/**
 * 
 * @author jorge
 *
 */
public class LoginAction extends AbstractAction {
	
  public ActionForward execute(ActionMapping actionMapping,
      ActionForm actionForm, HttpServletRequest request,
      HttpServletResponse response) {

    LoginActionForm form = (LoginActionForm) actionForm;
    ActionErrors errors = new ActionErrors();

    try {
      // Recupero el usuario y lo cargo en la session.
        
      UsuarioServices services = new UsuarioServices();
      Usuario usuario = services.obtenerUsuario(form.getLogin(), form.getPassword());

      request.getSession().setAttribute("usuarioConectado", usuario);

      // Forwardeo.
      return actionMapping.findForward("success");
    }
    catch (Exception ex) {
      ex.printStackTrace();	
      // Elimino el usuario de la session.
      request.getSession().removeAttribute("usuarioConectado");
      // Salvo los errores en el request.
      errors.add(ActionErrors.GLOBAL_MESSAGE, new ActionMessage("error.message", ex.getMessage()));
      saveErrors(request, errors);

      // Forwardeo.
      return actionMapping.findForward("failure");
    }
  }
}
